import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

// 创建仓库实例
const billStore = createSlice({
  name: 'bill',
  initialState: {
    billList: []
  },
  reducers: {
    // 添加账单
    addBill(state, action) {
      action.payload.id = Math.max(0, ...state.billList.map(v => v.id)) + 1
      state.billList.push(action.payload)
    },
    // 同步设置账单列表
    setBillList(state, action) {
      state.billList = action.payload
    }
  }
})

export const billStoreActions = {
  ...billStore.actions,
  // 异步获取账单列表
  getBillList() {
    return async (dispatch) => {
      const res = await axios({
        method: 'get',
        url: 'http://localhost:8888/ka'
      })
      dispatch(billStore.actions.setBillList(res.data))
    }
  }
}

export default billStore.reducer